<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAdd">新增菜单</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="菜单名称">
          <el-input v-model="queryForm.name" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-select v-model="queryForm.type" placeholder="请选择菜单类型" clearable>
            <el-option label="目录" value="DIRECTORY" />
            <el-option label="菜单" value="MENU" />
            <el-option label="按钮" value="BUTTON" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" row-key="id" default-expand-all>
        <el-table-column prop="name" label="菜单名称" min-width="200">
          <template #default="{ row }">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" />
        <el-table-column prop="component" label="组件路径" />
        <el-table-column prop="permission" label="权限标识" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 菜单表单弹窗 -->
    <el-dialog v-model="showDialog" :title="isEdit ? '编辑菜单' : '新增菜单'" width="700px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="formData.parentId"
                :data="menuTree"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                placeholder="请选择上级菜单"
                clearable
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="type">
              <el-select v-model="formData.type">
                <el-option label="目录" value="DIRECTORY" />
                <el-option label="菜单" value="MENU" />
                <el-option label="按钮" value="BUTTON" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标">
              <el-input v-model="formData.icon" placeholder="如：User" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="formData.type !== 'BUTTON'">
          <el-col :span="12">
            <el-form-item label="路由路径" prop="path">
              <el-input v-model="formData.path" placeholder="如：/system/user" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" v-if="formData.type === 'MENU'">
              <el-input v-model="formData.component" placeholder="如：system/user/Index" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input v-model="formData.permission" placeholder="如：system:user:list" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="formData.sort" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.status">
                <el-option label="显示" :value="1" />
                <el-option label="隐藏" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.type === 'MENU'">
            <el-form-item label="缓存">
              <el-select v-model="formData.keepAlive">
                <el-option label="开启" :value="1" />
                <el-option label="关闭" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" v-if="formData.type !== 'BUTTON'">
          <el-input v-model="formData.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { menuApi } from '@/api/menu'

const loading = ref(false)
const submitting = ref(false)
const showDialog = ref(false)
const isEdit = ref(false)
const tableData = ref([])
const menuTree = ref([])

const formRef = ref()

const queryForm = reactive({
  name: '',
  type: '',
  status: null
})

const formData = reactive({
  id: null,
  parentId: null,
  name: '',
  type: 'MENU',
  icon: '',
  path: '',
  component: '',
  permission: '',
  sort: 0,
  status: 1,
  keepAlive: 0,
  remark: ''
})

const formRules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
}

const getTypeTagType = (type) => {
  const typeMap = {
    'DIRECTORY': 'primary',
    'MENU': 'success',
    'BUTTON': 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeLabel = (type) => {
  const typeMap = {
    'DIRECTORY': '目录',
    'MENU': '菜单',
    'BUTTON': '按钮'
  }
  return typeMap[type] || type
}

const loadData = async () => {
  try {
    loading.value = true
    const response = await menuApi.getMenuTree(queryForm)
    tableData.value = response || []
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadMenuTree = async () => {
  try {
    const response = await menuApi.getMenuTree()
    menuTree.value = response || []
  } catch (error) {
    console.error('加载菜单树失败:', error)
  }
}

const handleSearch = () => {
  loadData()
}

const handleReset = () => {
  Object.assign(queryForm, {
    name: '',
    type: '',
    status: null
  })
  loadData()
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    id: null,
    parentId: null,
    name: '',
    type: 'MENU',
    icon: '',
    path: '',
    component: '',
    permission: '',
    sort: 0,
    status: 1,
    keepAlive: 0,
    remark: ''
  })
  showDialog.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formData, {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    type: row.type,
    icon: row.icon || '',
    path: row.path || '',
    component: row.component || '',
    permission: row.permission || '',
    sort: row.sort || 0,
    status: row.status,
    keepAlive: row.keepAlive || 0,
    remark: row.remark || ''
  })
  showDialog.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除菜单 ${row.name}？`, '提示')
    await menuApi.deleteMenu(row.id)
    ElMessage.success('删除成功')
    loadData()
    loadMenuTree()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await menuApi.updateMenu(formData)
      ElMessage.success('更新成功')
    } else {
      await menuApi.createMenu(formData)
      ElMessage.success('创建成功')
    }
    
    showDialog.value = false
    loadData()
    loadMenuTree()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadData()
  loadMenuTree()
})
</script>

<style scoped lang="scss">
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>